import {Request, Response, NextFunction, Router} from "express";
import multer from 'multer';
import path from "path";


let now = new Date(); //获取系统日期
let yy = now.getFullYear(); //获取年，即2007
let mm = now.getMonth() + 1; //获取月，即04
let dd = now.getDate(); //获取日，即29
let clock = yy + "-" + mm + "-" + dd;

let storage = multer.diskStorage({
    //文件保存绝对路径 不推荐
    // destination: function (req, file, cb) {
    //     cb(null, 'public/uploads/')
    // },


    //路径根据具体而定。如果不存在的话会自动创建一个路径
    destination: path.resolve(`public/uploads/${clock}/`),
    //修改文件名称
    filename: function (req: any, file: { originalname: any; }, cb: (arg0: null, arg1: string) => void) {
        var fileFormat = (file.originalname).split(".");
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})
// 加载配置
let upload = multer({storage: storage});


const upFilesRouterFactory =
    () => Router()
        .post('/upload', upload.single('file'), (req: Request, res: Response, next: NextFunction) => {
            try {
                res.send({
                    code:1,
                    filename: `http://localhost:5000/uploads/${clock}/` + req.file.filename
                })
            }catch (e) {
                res.send({
                    errCode: 10001,
                    msg: '图片上传失败'
                })
            }

        })

export default upFilesRouterFactory
